/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package me.bakumon.statuslayoutmanager;

import me.bakumon.statuslayoutmanager.library.OnStatusChildClickListener;
import me.bakumon.statuslayoutmanager.library.StatusLayoutManager;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.TextAlignment;
import ohos.agp.window.dialog.BaseDialog;
import ohos.agp.window.dialog.PopupDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.bundle.AbilityInfo;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.multimodalinput.event.TouchEvent;
import ohos.vibrator.agent.VibratorAgent;
import ohos.vibrator.bean.VibrationPattern;

import java.util.ArrayList;
import java.util.List;

/**
 * lipeiquan
 *
 * @since 2021-07-16
 */
public class MainAbility extends Ability {
    private SimpleRecyclerViewAdapter mAdapter;

    private final EventHandler mHandler = new EventHandler(EventRunner.getMainEventRunner());
    private List<String> mListManus;
    private PopupDialog mDialog;

    private StatusLayoutManager mStatusLayoutManager;
    private Component mIdDot;
    private ListContainer mRecyclerView;

    private boolean mIsLongClick;
    private boolean mIsShowMore;
    private long mMenusOnClickTime;
    private Component mIdMenus;
    private VibratorAgent mVibratorAgent;
    private Integer mVibratorId;
    private Component mIdDotTwo;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        getWindow().setStatusBarColor(Color.getIntColor("#323D9D"));
        initView();
        setupStatusLayoutManager();
        mStatusLayoutManager.showLoadingLayout();
        getData(1500);
        initVibrator();
    }

    private void initView() {
        mIdMenus = findComponentById(ResourceTable.Id_menus);
        mIdMenus.setTouchEventListener(new Component.TouchEventListener() {
            @Override
            public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
                int action = touchEvent.getAction();
                if (action == TouchEvent.PRIMARY_POINT_DOWN) {
                    mIsLongClick = true;
                    getUITaskDispatcher().delayDispatch(new Runnable() {
                        @Override
                        public void run() {
                            if (mIsLongClick) {
                                showMoreToastDialog("更多选项");
                                mIsShowMore = true;
                            }
                        }
                    }, 1000);
                } else if (action == TouchEvent.PRIMARY_POINT_UP) {
                    mIsShowMore = false;
                    mIsLongClick = false;
                }
                return false;
            }
        });
        mIdMenus.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (System.currentTimeMillis() - mMenusOnClickTime < 200) {
                    return;
                }
                mMenusOnClickTime = System.currentTimeMillis();
                if (!mIsShowMore) {
                    initDialog(mListManus);
                }
                mIsShowMore = false;
                mIsLongClick = false;
            }
        });
        mRecyclerView = (ListContainer) findComponentById(ResourceTable.Id_rv_content);
        mRecyclerView.setLongClickable(false);

        mIdDot = findComponentById(ResourceTable.Id_dot);
        mIdDotTwo = findComponentById(ResourceTable.Id_dot_two);
        initMenusData();
        mAdapter = new SimpleRecyclerViewAdapter(this, SimpleData.getRandomSonList(30), ResourceTable.Layout_item_list);
    }

    private void initDialog(List<String> list_manus) {
        Component mDialogComponent = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_layout_spinner, null, false);
        mDialogComponent.setAlpha(100);

        ListContainer text = (ListContainer) mDialogComponent.findComponentById(ResourceTable.Id_lc_spinner);
        text.setLongClickable(false);
        mDialog = new PopupDialog(this, mIdDot, 600, text.getHeight());
        mDialog.setCustomComponent(mDialogComponent);

        text.setItemProvider(new MyProvider(this, list_manus));
        text.setCanAcceptScrollListener((component, i, b) -> false);
        text.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int position, long l) {
                if (mDialog != null) {
                    mDialog.destroy();
                }
                onOptionsItemSelected(position);
            }
        });
        mDialog.setCornerRadius(10);
        mDialog.setTransparent(true);
        mDialog.setDialogListener(new BaseDialog.DialogListener() {
            @Override
            public boolean isTouchOutside() {
                if (mDialog != null) {
                    mDialog.destroy();
                }
                return false;
            }
        });
        mDialog.show();
    }

    @Override
    protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation) {
        super.onOrientationChanged(displayOrientation);
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.destroy();
            getUITaskDispatcher().delayDispatch(new Runnable() {
                @Override
                public void run() {
                    mIdMenus.callOnClick();
                }
            }, 200);
        }
    }

    private void onOptionsItemSelected(int position) {
        switch (position) {
            case 0:
                // 加载中
                mStatusLayoutManager.showLoadingLayout();
                break;
            case 1:
                // 空数据
                mStatusLayoutManager.showEmptyLayout();
                break;
            case 2:
                // 加载失败
                mStatusLayoutManager.showErrorLayout();
                break;
            case 3:
                // 加载成功，显示原布局
                mStatusLayoutManager.showSuccessLayout();
                break;
            case 4:
                // 自定义状态布局
                mStatusLayoutManager.showCustomLayout(ResourceTable.Layout_layout_custome, ResourceTable.Id_tv_customer, ResourceTable.Id_tv_customer1);
                break;
            default:
        }
    }

    private void initMenusData() {
        mListManus = new ArrayList<>();
        mListManus.add("加载中");
        mListManus.add("空数据");
        mListManus.add("出错");
        mListManus.add("加载成功");
        mListManus.add("自定义状态布局");
    }

    private void setupStatusLayoutManager() {
        mStatusLayoutManager = new StatusLayoutManager.Builder(mRecyclerView)
                .setOnStatusChildClickListener(new OnStatusChildClickListener() {
                    @Override
                    public void onEmptyChildClick(Component view) {
                        showToastDialog(getContext().getString(ResourceTable.String_reload_empty));
                        mStatusLayoutManager.showLoadingLayout();
                        getData(1000);
                    }

                    @Override
                    public void onErrorChildClick(Component view) {
                        showToastDialog(getContext().getString(ResourceTable.String_reload_error));
                        mStatusLayoutManager.showLoadingLayout();
                        getData(1000);
                    }

                    @Override
                    public void onCustomerChildClick(Component view) {
                        if (view.getId() == ResourceTable.Id_tv_customer) {
                            showToastDialog(getContext().getString(ResourceTable.String_request_access));
                        } else if (view.getId() == ResourceTable.Id_tv_customer1) {
                            showToastDialog(getContext().getString(ResourceTable.String_switch_account));
                        }

                    }
                })
                .build();
    }

    private void showToastDialog(String word) {
        getUITaskDispatcher().asyncDispatch(new Runnable() {
            @Override
            public void run() {
                ToastDialog toastDialog = new ToastDialog(getContext());
                toastDialog.setTransparent(true);
                DependentLayout dependentLayout = new DependentLayout(getContext());
                dependentLayout.setComponentSize(ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_PARENT);

                Text text = new Text(getContext());
                DependentLayout.LayoutConfig layoutConfig = new DependentLayout.LayoutConfig();
                layoutConfig.addRule(DependentLayout.LayoutConfig.ALIGN_PARENT_BOTTOM);
                layoutConfig.addRule(DependentLayout.LayoutConfig.HORIZONTAL_CENTER);
                text.setLayoutConfig(layoutConfig);
                text.setTextAlignment(TextAlignment.CENTER);
                text.setTextSize(50);
                text.setWidth(ComponentContainer.LayoutConfig.MATCH_CONTENT);
                text.setHeight(ComponentContainer.LayoutConfig.MATCH_CONTENT);
                text.setText(word);
                text.setMarginBottom(250);
                text.setPadding(80, 30, 80, 30);
                ShapeElement shapeElement = new ShapeElement();
                shapeElement.setCornerRadius(70);
                shapeElement.setRgbColor(RgbColor.fromArgbInt(Color.getIntColor("#EFEFEF")));
                text.setBackground(shapeElement);

                dependentLayout.addComponent(text);
                toastDialog.setSize(ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_PARENT);
                toastDialog.setComponent(dependentLayout);
                toastDialog.show();
            }
        });
    }

    private void showMoreToastDialog(String word) {
        if (hasVibrator()) {
            startVibrator();
        }
        PopupDialog toastDialog = new PopupDialog(getContext(), mIdDotTwo);
        DependentLayout dependentLayout = new DependentLayout(getContext());
        dependentLayout.setComponentSize(ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_PARENT);

        Text text = new Text(getContext());
        DependentLayout.LayoutConfig layoutConfig = new DependentLayout.LayoutConfig();
        layoutConfig.addRule(DependentLayout.LayoutConfig.ALIGN_PARENT_RIGHT);
        text.setLayoutConfig(layoutConfig);
        text.setTextAlignment(TextAlignment.CENTER);
        text.setTextSize(45);
        text.setWidth(ComponentContainer.LayoutConfig.MATCH_CONTENT);
        text.setHeight(ComponentContainer.LayoutConfig.MATCH_CONTENT);
        text.setText(word);
        text.setPadding(38, 18, 38, 18);
        text.setTextColor(Color.WHITE);
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setCornerRadius(8);
        shapeElement.setRgbColor(RgbColor.fromArgbInt(Color.getIntColor("#707070")));
        text.setBackground(shapeElement);

        dependentLayout.addComponent(text);
        toastDialog.setCustomComponent(dependentLayout);
        toastDialog.setTransparent(true);
        toastDialog.setCornerRadius(8);
        toastDialog.setSize(256, 96);
        toastDialog.setDialogListener(new BaseDialog.DialogListener() {
            @Override
            public boolean isTouchOutside() {
                if (toastDialog != null) {
                    toastDialog.destroy();
                }
                return false;
            }
        });
        toastDialog.show();
        getUITaskDispatcher().delayDispatch(new Runnable() {
            @Override
            public void run() {
                if (toastDialog != null) {
                    toastDialog.destroy();
                }
            }
        }, 2000);
    }

    private void getData(final long time) {
        mHandler.postTask(new Runnable() {
            @Override
            public void run() {
                mRecyclerView.setItemProvider(mAdapter);
                mStatusLayoutManager.showSuccessLayout();
            }
        }, time);
    }

    private void initVibrator() {
        mVibratorAgent = new VibratorAgent();
        // 查询硬件设备上的振动器列表
        List<Integer> vibratorList = mVibratorAgent.getVibratorIdList();
        if (vibratorList.isEmpty()) {
            mVibratorAgent = null;
            return;
        }
        mVibratorId = vibratorList.get(0);
    }

    private boolean hasVibrator() {
        // 查询指定的振动器是否支持指定的振动效果
        return mVibratorAgent.isEffectSupport(mVibratorId,
                VibrationPattern.VIBRATOR_TYPE_CAMERA_CLICK);
    }

    private void startVibrator() {
        // 创建指定振动时长的一次性振动
        mVibratorAgent.startOnce(mVibratorId, 1);
    }

}
